// 定义一个用户相关的仓库
import { defineStore } from "pinia";
// 引入获取验证码的请求方法
import { reqUserCode, reqUserLogin } from "@/api/hospital";
import type { LoginData, UserLoginResponeseData } from "@/api/hospital/type";
import type { UserState } from './interface'
const userStore = defineStore('User', {
    state: (): UserState => {
        return {
            // 用于控制登录组件的dialog的显示与隐藏
            visiable: false,
            // 存储用户的验证码
            code: '', 
            userInfo: JSON.parse(localStorage.getItem('USERINFO') as string) || {}
        }
    },
    actions: {
        // 获取服务器携带的手机号码，获取验证码
        async getCode(phone: string) {
            const result: any = await reqUserCode(phone)
            if (result.code == 200) {
                this.code = result.data
                return 'ok'
            } else {
                Promise.reject(new Error(result.message))
            }

        },

        async userLogin(loginData: LoginData) {
            const result: UserLoginResponeseData = await reqUserLogin(loginData)
            if (result.code == 200) {
                this.userInfo = result.data
                // 本地存储持久化用户信息
                localStorage.setItem('USERINFO',JSON.stringify(this.userInfo))
                // 返回一个成功的promise
                return 'ok'
            }else{
                return Promise.reject(new Error(result.message))
            }

        },

        logout(){
            this.userInfo = { name:'', token:''}
            localStorage.removeItem('USERINFO')
            
        }
    },
    getters: {

    }
});

export default userStore